package cn.sample.security.json.handler;

import cn.sample.common.properties.SysProperties;
import cn.sample.common.result.JsonResult;
import cn.sample.common.result.ResultCode;
import cn.sample.system.bean.User;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <h2></h2>
 *
 * <p>认证成功处理器</p>
 *
 * @author HKD
 */
@Component
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private SysProperties sysProperties;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = (String) authentication.getPrincipal();
        User user = (User) authentication.getDetails();

        // 封装返回参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        jsonObject.put("user",user);
        jsonObject.put("resource",null);

        //返回Json格式
        response.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(JsonResult.result(ResultCode.SUCCESS.getCode(),"登录成功",jsonObject)));
        writer.flush();
        writer.close();
    }
}
